﻿
using DataBase.DBmodels;
using DataBase.Utils;
using GalaSoft.MvvmLight.Command;
using GreenXi.Help.Curve;
using GreenXi.Model;
using HandyControl.Controls;
using LiveCharts;
using LiveCharts.Wpf;
using Microsoft.Win32;
using Prism.Commands;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using LiveCharts.Defaults;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Imaging;



namespace GreenXi.ViewModel
{
    public class CustomerVm : CustomerVmModel
    {


        #region  折线
        public LineSeries Line()
        {
            //实例化一条折线图
            LineSeries mylineseries = new LineSeries();
            //设置折线的标题
            mylineseries.Title = "工位合格数";
            mylineseries.Fill = Brushes.Transparent;

            //设置折线粗细
            mylineseries.StrokeThickness = 1;
            //设置折线颜色
            //mylineseries.Stroke =Brushes.Gray;
            //设置折线是否光滑
            mylineseries.LineSmoothness = 0;
            //折线图直线形式
            //mylineseries.LineSmoothness = 0;

            //折线图的无点样式
            mylineseries.PointGeometry = null;
            return mylineseries;
        }
        #endregion

        public void Data()
        {
            int year = 0;
            int month = 0;
            if (CraftId == 0)
            {
                CraftId = CraftList.FirstOrDefault().Id;
            }
            if (Year == null && Month == null)
            {
                year = DateTime.Now.Year;
                month = DateTime.Now.Month;
            }
            else
            {
                year = Convert.ToInt32(Year);
                month = Convert.ToInt32(Month);
            }

            int days = 0;
            string unti = "";
            if (Type == null){
                Type = "日";
            }
            colhSeries = new ChartValues<double>();
            //线条样式
            StackedColumnSeries mylineseries = new StackedColumnSeries();
            mylineseries.Values = colhSeries;


            //计算纵坐标
            if (Type.Contains("日"))
            {
                unti = "日";
                mylineseries.Title = $"{StartTime.Value.ToString("yyyy-MM-dd")}到{EndTime.Value.ToString("yyyy-MM-dd")}{unti}用电量";
                List<DateTime> dates = new List<DateTime>();
                for (DateTime date = StartTime.Value; date <= EndTime; date = date.AddDays(1))
                {
                    dates.Add(date);
                }
                days = dates.Count();
                colhLabels = new string[days];
                var model = MyDbContext.Instance.GetElectricityData(CraftId, StartTime.Value, EndTime.Value);
                for (int i = 0; i < days; i++)
                {
                    colhLabels[i] = dates[i].ToString("MM-dd") ;
                    var Result = model.Where(x => x.CreateTime.Value.Day == dates[i].Day&& x.CreateTime.Value.Month == dates[i].Month).FirstOrDefault();
                    double Disqu = Result == null ? 0 : Result.ElectricityConsumption;
                    colhSeries.Add(Disqu);
                }
            }
            if (Type.Contains("月"))
            {
                unti = "月";
                mylineseries.Title = $"{StartTime.Value.ToString("yyyy-MM")}到{EndTime.Value.ToString("yyyy-MM")}{unti}用电量";
                var dates = GetYearMonthRange(StartTime.Value, EndTime.Value);
                days = dates.Count();
                colhLabels = new string[days];
                var model = MyDbContext.Instance.GetElectricityData(CraftId, StartTime.Value, EndTime.Value);
                for (int i = 0; i < days; i++)
                {
                    colhLabels[i] = dates[i].ToString("yyyy-MM") + "月";
                    var Result = model.Where(x => x.CreateTime.Value.Month == dates[i].Month).Sum(x => x.ElectricityConsumption);
                    double Disqu = Result;
                    colhSeries.Add(Disqu);
                }
            }
            if (Type.Contains("年"))
            {
                unti = "年";
                mylineseries.Title = $"{StartTime.Value.ToString("yyyy")}到{EndTime.Value.ToString("yyyy")}{unti}用电量";

                var dates = GetYearRange(StartTime.Value, EndTime.Value);
                days = dates.Count();

                colhLabels = new string[days];
                var model = MyDbContext.Instance.GetElectricityData(CraftId,StartTime.Value,EndTime.Value);
                
                for (int i = 0; i < days; i++)
                {
                    colhLabels[i] = dates[i].ToString("yyyy") + "年";
                    var Result = model.Where(x => x.CreateTime.Value.Year == dates[i].Year).Sum(x => x.ElectricityConsumption);
                    double Disqu = Result;
                    colhSeries.Add(Disqu);
                }
               
            }

          
          

            SeriesCollection = new SeriesCollection { };
            SeriesCollection.Add(mylineseries);

         
        }
        public void DYData()
        {
            List<timeData> datalist = new List<timeData>();
            var date = DateTime.Now.Year;
            int year = 2040;
            for (int i = 0; i <= year - 2020; i++)
            {
                timeData time = new timeData() { yeser = (2020 + i).ToString() };
                datalist.Add(time);
            }
            Yearshare = datalist;
        }

        #region 折线图
        public void LineChart()
        {

            int year = 0;
            int month = 0;
            if (CraftId == 0)
            {
                CraftId = CraftList.FirstOrDefault().Id;
            }
            if (YearLine == null && YearLine == null)
            {
                year = DateTime.Now.Year;
                month = DateTime.Now.Month;
            }
            else
            {
                year = Convert.ToInt32(YearLine);
                month = Convert.ToInt32(MonthLine);
            }
            int days = 0;
            string unti = "";
            if (Type == null)
            {
                Type = "日";
            }
            colhSeries = new ChartValues<double>();
            //线条样式
            var mylineseries = Line();

        
            //计算纵坐标
            if (Type.Contains("日"))
            {
                unti = "日";
                mylineseries.Title = $"{StartTime.Value.ToString("yyyy-MM-dd")}到{EndTime.Value.ToString("yyyy-MM-dd")}{unti}用电量";
                List<DateTime> dates = new List<DateTime>();
                for (DateTime date = StartTime.Value; date <= EndTime; date = date.AddDays(1))
                {
                    dates.Add(date);
                }
                days = dates.Count();
                colhLabels = new string[days];
                var model = MyDbContext.Instance.GetElectricityData(CraftId, StartTime.Value, EndTime.Value);
                for (int i = 0; i < days; i++)
                {
                    colhLabels[i] = dates[i].ToString("MM-dd");
                    var Result = model.Where(x => x.CreateTime.Value.Day == dates[i].Day && x.CreateTime.Value.Month == dates[i].Month).FirstOrDefault();
                    double Disqu = Result == null ? 0 : Result.ElectricityConsumption;
                    colhSeries.Add(Disqu);
                }
            }
            if (Type.Contains("月"))
            {
                unti = "月";
                mylineseries.Title = $"{StartTime.Value.ToString("yyyy-MM")}到{EndTime.Value.ToString("yyyy-MM")}{unti}用电量";
                var dates = GetYearMonthRange(StartTime.Value, EndTime.Value);
                days = dates.Count();
                colhLabels = new string[days];
                var model = MyDbContext.Instance.GetElectricityData(CraftId, StartTime.Value, EndTime.Value);
                for (int i = 0; i < days; i++)
                {
                    colhLabels[i] = dates[i].ToString("yyyy-MM") + "月";
                    var Result = model.Where(x => x.CreateTime.Value.Month == dates[i].Month).Sum(x => x.ElectricityConsumption);
                    double Disqu = Result;
                    colhSeries.Add(Disqu);
                }
            }
            if (Type.Contains("年"))
            {
                unti = "年";
                mylineseries.Title = $"{StartTime.Value.ToString("yyyy")}到{EndTime.Value.ToString("yyyy")}{unti}用电量";

                var dates = GetYearRange(StartTime.Value, EndTime.Value);
                days = dates.Count();

                colhLabels = new string[days];
                var model = MyDbContext.Instance.GetElectricityData(CraftId, StartTime.Value, EndTime.Value);

                for (int i = 0; i < days; i++)
                {
                    colhLabels[i] = dates[i].ToString("yyyy") + "年";
                    var Result = model.Where(x => x.CreateTime.Value.Year == dates[i].Year).Sum(x => x.ElectricityConsumption);
                    double Disqu = Result;
                    colhSeries.Add(Disqu);
                }

            }


            YMax = colhSeries.Max();

            //添加折线图的数据
            mylineseries.Values = new ChartValues<double>(colhSeries); //绑定数据



            PolylinSeries = new SeriesCollection { };
           
            PolylinSeries.Add(mylineseries);
        }

        #endregion

        public CustomerVm()
        {
            try
            {
                // 检查日期是否已选择
                if (!StartTime.HasValue || !EndTime.HasValue)
                {
                    System.Windows.Forms.MessageBox.Show("请选择开始和结束日期！");
                    return;
                }
                // 确保开始日期不晚于结束日期
                if (StartTime > EndTime)
                {
                    (StartTime, EndTime) = (EndTime, StartTime); // 交换日期
                }



                CraftList = new(MyDbContext.GetCraftViewByType(5));
                var year2 = Year;
                DYData();
                #region  柱状图
                QueryCommand = new DelegateCommand(() =>
                    {
                        if (Year == null || Year == "")
                        {
                            Year = DateTime.Now.Year.ToString();

                        }
                        if (Month == null || Month == "")
                        {
                            Month = DateTime.Now.Month.ToString();
                        }
                        YMshare = Year + "/" + Month;

                        Data();

                    });

                //导出图标

                ExportChartCommand = new RelayCommand<CartesianChart>(ExportChart);


                XPointer = -5;
                YPointer = -5;
                Formatter = x => x.ToString("N2");
                if (year2 == null || year2 == "")
                {

                }
                else
                {
                    title = DateTime.Now.Month.ToString() + "月份的用电情况";
                    DisTitle = DateTime.Now.Month.ToString() + "月份的不合格情况";
                    Data();

                    #endregion
                }
            }
            catch (Exception ex)
            {

				Helpers.Logger.Instance.Warning($"Catch CustomerVm {ex.Message}");
			}


            #region  折线图
            LineCommand = new DelegateCommand(() =>
                {
                    if (YearLine == null || YearLine == "")
                    {
                        YearLine = DateTime.Now.Year.ToString();
                    }
                    if (MonthLine == null || MonthLine == "")
                    {
                        MonthLine = DateTime.Now.Month.ToString();
                    }
                    LMshare = YearLine + "/" + MonthLine;

                    LineChart();
                });
            #endregion
        }


        private void ExportChart(CartesianChart chart)
        {
            //背景色，chart是前台按钮绑定参数传过来的
            chart.Background = System.Windows.Media.Brushes.White;
          
        
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "图片另存为";
            saveFileDialog.Filter = "jpg图片|*.JPG|png图片|*.PNG|jpeg图片|*.JPEG";
            saveFileDialog.FilterIndex = 2;
            saveFileDialog.RestoreDirectory = true;//保存对话框是否记忆上次打开的目录
            Nullable<bool> result = saveFileDialog.ShowDialog();//因为是WPF，相当于OK
            if (result == true)
            {
                FileStream fs = new FileStream($"{saveFileDialog.FileName}", FileMode.Create);//要保存的路径
                                                                                              //对象转换成位图
                RenderTargetBitmap bmp = new RenderTargetBitmap((int)chart.ActualWidth + 10, (int)chart.ActualHeight + 10, 96, 96, PixelFormats.Pbgra32);
                bmp.Render(chart);
                //对象的集合编码转成图像流
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                //保存到路径中
                encoder.Save(fs);
                //释放资源
                fs.Close();
                fs.Dispose();
                System.Windows.Forms.MessageBox.Show("保存成功");
            }
        }
        public List<DateTime> GetYearMonthRange(DateTime startDate, DateTime endDate)
        {

            List<DateTime> result = new List<DateTime>();
            // 转换为每月第一天进行比较
            var current = new DateTime(startDate.Year, startDate.Month, 1);
            var end = new DateTime(endDate.Year, endDate.Month, 1);

            while (current <= end)
            {
                result.Add(current);
                current = current.AddMonths(1);
            }

            return result;
        }

        public List<DateTime>  GetYearRange(DateTime startDate, DateTime endDate)
        {
            // 计算开始和结束年份
            int startYear = startDate.Year;
            int endYear = endDate.Year;

            // 生成年份列表
            List<DateTime> years = new List<DateTime>();
            for (int year = startYear; year <= endYear; year++)
            {
                years.Add(new DateTime(year, 1, 1));
            }

            return years;
        }
    }

}
